// perl_appeventsink.cpp - app event sink

#include "PlPN.h"

/*
 * PerlAppEventSink
 */
 
PerlAppEventSink::PerlAppEventSink() {}

PerlAppEventSink::~PerlAppEventSink() {}

void PerlAppEventSink::OnNewDocument(extensions::IDocumentPtr& doc) {
	// may have already been added by OnDocSelected, so check first
	TrackedDocument* tdoc = g_document_tracker.Fetch(doc);
	// if it's not being tracked, start tracking it
	if (tdoc == NULL) {
		g_document_tracker.Add(doc, &tdoc);
	}
	
	// call the event for every perl sink we're tracking
	for (int i = 0; i < m_perl_sinks.size(); i++) {	
		dSP;

		ENTER;
		SAVETMPS;

		PUSHMARK(SP);
		XPUSHs(m_perl_sinks[i]);
		XPUSHs(tdoc->perl_doc);
		PUTBACK;
	
		call_method("OnNewDocument", G_VOID|G_EVAL);
		SPAGAIN;

		if(SvTRUE(ERRSV)) {
			STRLEN n_a;
			alert("Error calling Perl version of OnNewDocument: %s\n", SvPV(ERRSV,n_a));
		}
	
		PUTBACK;
		FREETMPS;
		LEAVE;
	}

	return;
}

void PerlAppEventSink::OnAppClose() {
	// call the event for every perl sink we're tracking
	for (int i = 0; i < m_perl_sinks.size(); i++) {
		dSP;

		ENTER;
		SAVETMPS;

		PUSHMARK(SP);
		XPUSHs(m_perl_sinks[i]);
		PUTBACK;
	
		call_method("OnAppClose", G_VOID|G_EVAL);
		SPAGAIN;

		if(SvTRUE(ERRSV)) {
			STRLEN n_a;
			alert("Error calling Perl version of OnAppClose: %s\n", SvPV(ERRSV,n_a));
		}
		
		PUTBACK;
		FREETMPS;
		LEAVE;
	}

	return;
}

void PerlAppEventSink::OnDocSelected(extensions::IDocumentPtr& doc) {
	// may have already been added by OnNewDocument, so check first
	TrackedDocument* tdoc = g_document_tracker.Fetch(doc);
	// if it's not being tracked, start tracking it
	if (tdoc == NULL) {
		g_document_tracker.Add(doc, &tdoc);
	}
	
	// call the event for every perl sink we're tracking
	for (int i = 0; i < m_perl_sinks.size(); i++) {
		dSP;

		ENTER;
		SAVETMPS;

		PUSHMARK(SP);
		XPUSHs(m_perl_sinks[i]);
		XPUSHs(tdoc->perl_doc);
		PUTBACK;
	
		call_method("OnDocSelected", G_VOID|G_EVAL);
		SPAGAIN;

		if(SvTRUE(ERRSV)) {
			STRLEN n_a;
			alert("Error calling Perl version of OnDocSelected: %s\n", SvPV(ERRSV,n_a));
		}
	
		PUTBACK;
		FREETMPS;
		LEAVE;
	}
	
	return;
}

void PerlAppEventSink::OnFirstEditorCreated(HWND hWndScintilla) {
	// call the event for every perl sink we're tracking
	for (int i = 0; i < m_perl_sinks.size(); i++) {	
		dSP;

		ENTER;
		SAVETMPS;
		
		PUSHMARK(SP);
		XPUSHs(m_perl_sinks[i]);
		XPUSHs(sv_2mortal(newSViv((int)hWndScintilla)));
		PUTBACK;
	
		call_method("OnFirstEditorCreated", G_VOID|G_EVAL);
		SPAGAIN;

		if(SvTRUE(ERRSV)) {
			STRLEN n_a;
			alert("Error calling Perl version of OnFirstEditorCreated: %s\n", SvPV(ERRSV,n_a));
		}
	
		PUTBACK;
		FREETMPS;
		LEAVE;
	}
	
	return;
}
